package repository

import (
	"boy-go/modules/demo/model"
	"boy-go/modules/demo/vo"
	"boy-go/pkg/db"
	"boy-go/pkg/request"
	"gorm.io/gorm"
)

var (
	// 查询字段SQL
	_selectTSchoolVo = "id, name, level, ext, address, create_time, update_time"
)

type TSchoolRepository struct {
	DB *gorm.DB
}

func NewTSchoolRepository() *TSchoolRepository {
	return &TSchoolRepository{
		DB: db.GetMasterDB(),
	}
}
func (r *TSchoolRepository) GetById(id int64) (*model.TSchool, error) {
	db := r.DB
	m := &model.TSchool{}
	err := db.Model(&model.TSchool{}).Where("id = ?", id).First(m).Error
	if err != nil {
		return nil, err
	}
	return m, nil
}

func (r *TSchoolRepository) List(query *vo.QueryTSchoolReq, pageReq *request.PageRequest) ([]*model.TSchool, int64, error) {
	tx := r.DB.Model(&model.TSchool{})
	if query != nil {
		if query.Name != nil {
			tx = tx.Where("name like ?", "%"+*query.Name+"%")
		}
		if query.Level != nil {
			tx = tx.Where("level = ?", *query.Level)
		}
		if query.Ext != nil {
			tx = tx.Where("ext = ?", *query.Ext)
		}
		if query.Address != nil {
			tx = tx.Where("address = ?", *query.Address)
		}
		if query.Params != nil {
		}
	}
	list := make([]*model.TSchool, 0)
	if pageReq != nil {
		var total int64
		if err := tx.Count(&total).Error; err != nil {
			return nil, 0, err
		}
		if total > 0 {
			tx = tx.Select(_selectTSchoolVo)
			tx = db.BuildPageAndOrder(tx, &query.PageRequest, "")
			if err := tx.Find(&list).Error; err != nil {
				return nil, total, err
			}
		}
		return list, total, nil
	} else {
		tx = tx.Select(_selectTSchoolVo)
		if err := tx.Find(&list).Error; err != nil {
			return nil, 0, err
		}
	}
	return list, int64(len(list)), nil
}

// ListTSchoolTagBySchoolId 根据SchoolId 获取子表数据
func (r *TSchoolRepository) ListTSchoolTagBySchoolId(schoolId int64) ([]*model.TSchoolTag, error) {
	list := make([]*model.TSchoolTag, 0)
	err := r.DB.Model(&model.TSchoolTag{}).Where("school_id = ?", schoolId).Find(&list).Error
	return list, err
}

// Save 添加
func (r *TSchoolRepository) Save(m *model.TSchool) error {
	return r.DB.Model(&model.TSchool{}).Create(m).Error
}

// Update 更新
func (r *TSchoolRepository) Update(m *model.TSchool) error {
	return r.DB.Model(&model.TSchool{}).Where("id = ?", m.Id).Omit("id").Updates(m).Error
}

// Delete 删除
func (r *TSchoolRepository) Delete(id int64) error {
	return r.DB.Model(&model.TSchool{}).Where("id = ?", id).Delete(&model.TSchool{}).Error
}

// DeleteBatch 批量删除
func (r *TSchoolRepository) BatchDelete(ids []string) error {
	db := r.DB
	db = db.Where("(id) IN ?", ids)
	return db.Delete(&model.TSchool{}).Error
}
